import { NextResponse } from 'next/server';
import blogModule from '@/modules/blog';
import generateSlugify from '@/utils/generateSlugify'

export async function GET(request) {
  const codeMap = { 0: '获取成功', 1: '内容为空', };
  const { searchParams } = new URL(request.url);
  const page = searchParams.get('page') || 1;
  const limit = searchParams.get('limit') || 10;
  const offset = (page - 1) * limit;
  const blogs = await blogModule.getAll(Number(limit), Number(offset));
  if (!blogs) { return NextResponse.json({ code: 1,codeMap, message: 'No blogs found' }); }
  return NextResponse.json({ code: 0,codeMap, message: 'Success', data: blogs.blogs, total: blogs.total, });
}

export async function PUT(request) {
  const codeMap = { 0: '更新成功', 1: '博客未找到', 2: '标题不能为空' };
  const { id, slug: originSlug, title, description, template, status, cover, sort, meta_title, meta_description } = await request.json();
  const blog = await blogModule.getById(Number(id));
  if (!blog) { return NextResponse.json({ code: 1, codeMap, message: 'No blog found' }); }
  if (!title) { return NextResponse.json({ code: 2, codeMap, message: 'Title cannot be empty' }); }
  const slugList = await blogModule.getSlugs();
  const slug = !originSlug ? await generateSlugify(title, slugList) : originSlug;
  const result = await blogModule.updateById(id, { slug, title, description, template, status, cover, sort, meta_title, meta_description });
  if (result.affectedRows === 0) { return NextResponse.json({ code: 1, codeMap, message: 'Update failed' }); }
  const newBlog = await blogModule.getById(Number(id));
  return NextResponse.json({ code: 0, codeMap, message: 'Success', data: newBlog });
}

export async function DELETE(request) {
  const { id } = await request.json();
  const codeMap = { 0: '删除成功', 1: '博客不存在', 2: "删除失败" };
  const isHas = await blogModule.getById(id);
  if (!isHas) { return NextResponse.json({ code: 1, codeMap, message: 'No articles found' }); }
  const result = await blogModule.deleteById(id);
  if (result.affectedRows === 0) { return NextResponse.json({ code: 2, codeMap, message: 'Delete failed' }); }
  return NextResponse.json({ code: 0, codeMap, message: 'Delete success' });
}

export async function POST(request) {
  const codeMap = { 0: '创建成功', 1: '标题不能为空', 2: '创建失败' };
  const { title, description } = await request.json();
  if (!title) { return NextResponse.json({ code: 1, codeMap, message: 'Title cannot be empty' }); }
  const blog = await blogModule.create({ slug : null, title, description, template: 'default', status : 1, cover : '', sort : 0, meta_title : '', meta_description : '' });
  if (!blog) { return NextResponse.json({ code: 2, codeMap, message: 'Create failed' }); }
  return NextResponse.json({ code: 0, codeMap, message: 'Success', id: blog.insertId });
}